import axios from "axios";
import { ElMessage } from "element-plus";
import qs from "qs";
import { getToken, setToken, getAllToken } from "@/utils/auth";

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_URl, // api 的 base_url
  timeout: 30000, // 请求超时时间
  withCredentials: false, // 禁用 Cookie 等信息
});

// request拦截器
service.interceptors.request.use(
  (config) => {
    config.headers["tenant-id"] = "1";
    if (getToken() && !config.headers.Authorization) {
      config.headers.Authorization = "Bearer " + getToken();
    }
    const params = config.params || {};
    const data = config.data || false;
    if (
      config.method?.toUpperCase() === "POST" &&
      config.headers["Content-Type"] === "application/x-www-form-urlencoded"
    ) {
      config.data = qs.stringify(data);
    }
    // get参数编码
    if (config.method?.toUpperCase() === "GET" && params) {
      config.params = {};
      const paramsStr = qs.stringify(params, { allowDots: true });
      if (paramsStr) {
        config.url = config.url + "?" + paramsStr;
      }
    }
    return config;
  },
  (error) => {
    // Do something with request error
    console.log(error); // for debug
    Promise.reject(error);
  }
);
// 创建一个Set用于跟踪正在刷新的请求
const pendingRequests = new Set();
// response 拦截器
service.interceptors.response.use(
  async (response) => {
    let { data } = response;
    if (!data) {
      throw new Error();
    }
    const code = data.code !== undefined ? data.code : data.Code;
    const msg = data.msg || data.Msg || data.message || data.Message;
    // 绑定手机号请求 需要错误信息进行下一步
    if (response.config.url.indexOf("bindPhone") != -1) {
      return data;
    } else if (code == 401 && !pendingRequests.has(response.config.url)) {
      pendingRequests.add(response.config.url);
      try {
        let { data } = await service.post("/ssosystem/auth/login", {
          accessToken: getAllToken().accessToken,
        });
        let res = await service.post("/system/auth/refresh-token?refreshToken=" + data.refreshToken);
        setToken(res.data.accessToken)
        axios.defaults.headers.common['Authorization'] = 'Bearer ' + res.data.accessToken;
        response.config.headers.Authorization = 'Bearer ' + res.data.accessToken;
        return service(response.config); // 重新执行原始请求
      } catch (err) {
        ElMessage.error("刷新Token失败，请重新登录");
      } finally {
        pendingRequests.delete(response.config.url);
      }
    }
    else if (code !== 0 && code !== 200) {
      ElMessage.error(msg);
      // return Promise.reject(new Error(msg))
    }
    return data;
  },
  (error) => {
    console.log("err" + error);
    return Promise.reject(error);
  }
);

export { service };
